--[[ Return a coroutine the returns the next Fibonacci number per call.

Could have been implemented as a closure by having variables hold what was to
be returned per call of the inner function and mutating the local variables in
the outer function.
--]]
function fibonacci()
    return coroutine.create(
	function ()
	    local minus_1 = 1
	    local minus_2 = 0
	    while true do
		local fib = minus_1 + minus_2
		coroutine.yield(minus_2)
		minus_2 = minus_1
		minus_1 = fib
	    end
	end
    )
end

if type(arg) ~= nil then
    --[[ Return an iterator closure that calls the specified coroutine count
    times.

    Iterator protocol richer than this, but other parts unneeded and Lua's
    behaviour of assigning nil for all unused variables in multiple assignment
    allows for simpler usage.
    --]]
    local function coroutine_iterator(co, count)
	return function ()
		if count > 0 then
		    count = count - 1  -- no augmented assignment
		    return coroutine.resume(co)
		else
		    return nil
		end
	    end
    end

    for state, fib_num in coroutine_iterator(fibonacci(), tonumber(arg[1])+1) do
	if not state then
	    error(fib_num)
	else
	    io.write(fib_num .. ' ')  -- print() always appends \n
	end
    end
    io.write("...\n")
end
